package com.ylz.sjzx.sio.sdk.client.engine;

import com.corundumstudio.socketio.transport.NamespaceClient;
import com.ylz.sjzx.sio.common.core.enums.SocketModel;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import com.ylz.sjzx.sio.sdk.client.utils.SessionUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wiqi
 * @version 1.0
 * @date 2020/12/8
 */
@Slf4j
public final class ChatEngineManager {

    /**
     * 所有的聊天室引擎管理中心
     */
    private static Map<String, ChatEngine> chatEngineManager = new HashMap();

    /**
     * 总能获取到获取对应的聊天室 没有聊天室就创建
     *
     * @param chatRoomId
     * @return
     */
    public static ChatEngine alwaysGetChatEngine(String chatRoomId, SocketModel socketModel) {
        ChatEngine chatEngine0 = chatEngineManager.get(chatRoomId);
        if (chatEngine0 == null) {
            synchronized (chatRoomId.intern()) {
                chatEngine0 = chatEngineManager.get(chatRoomId);
                if (chatEngine0 == null) {
                    chatEngine0 = getChatEngine(chatRoomId, socketModel);
                    chatEngineManager.put(chatRoomId, chatEngine0);
                }
            }
        }

        return chatEngine0;
    }

    /**
     * 移除聊天组
     *
     * @param chatRoomId
     * @param chatRoomGroup
     */
    public static void removeChatRoomGroup(String chatRoomId, String chatRoomGroup, SocketModel socketModel) {
        ChatEngine chatEngine = alwaysGetChatEngine(chatRoomId, socketModel);
        chatEngine.removeGroup(chatRoomGroup);
    }

    /**
     * 将用户添加如聊天组
     */
    public static ChatEngine add2ChatRoomGroup(IMSession session) {
        ChatEngine chatEngine = alwaysGetChatEngine(session.getRoomName(), session.getSocketModel());

        if (session.getSocketModel() == SocketModel.socketIo) {
            Channel channle = SessionUtil.getChannle((NamespaceClient) session.getSocketIOClient());
            session.setChannel(channle);
        }
        log.debug("加入我们聊天室么{}", session);
        return chatEngine.add2ChatRoomGroup(session);
    }

    /**
     * 将用户从聊天室移除
     */
    public static void removeFromChatRoomGroup(IMSession session) {
        ChatEngine chatEngine = alwaysGetChatEngine(session.getRoomName(), session.getSocketModel());
        chatEngine.removeFromChatRoomGroup(session);
    }

    private static ChatEngine getChatEngine(String chatRoomId, SocketModel socketModel) {
        ChatEngine chatEngine = null;
        switch (socketModel) {
            case channel:
                chatEngine = new ChannelChatEngine(chatRoomId);
                break;

            default:
                chatEngine = new SocketIoChatEngine(chatRoomId);
                break;
        }
        return chatEngine;
    }

    /**
     * 清理在线聊天室
     */
    public static void clean() {
        chatEngineManager = new HashMap();
    }
}
